<template>
  <div class="app-container bg">
    <div class="box-container">
      <div
        class="mb15"
        style="border-bottom: 1px solid #ddd; margin-bottom: 10px"
      >
        <el-radio-group
          v-model="showType"
          class="custom-radio-group"
          @change="showTypeChange"
        >
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2">学员</el-radio-button>
        </el-radio-group>
      </div>

      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="font-size: 14px; line-height: 25px"
      >
        <el-col :span="2.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ registerBaseVo.total || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(1, 1)"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            待评价：{{ registerBaseVo.evaluateStatus1 || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(2, 2)"
            class="nactive"
            :class="{ active: tagIndex == 2 }"
          >
            已评价：{{ registerBaseVo.evaluateStatus2 || 0 }}
          </div>
        </el-col>
      </el-row>

      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            :disabled="multiple"
            type="primary"
            size="mini"
            @click="sendBatchOpen"
            >批量通知</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="settingOpen"
            >设置评价时间</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="evaluateOpen"
            >查看评价表单</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label=""
        style="width: 160px"
        prop="registerTypeId"
        v-if="false"
      >
        <el-select
          v-model="queryParams.registerTypeId"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerTypeList"
            :key="index"
            :label="item.registerTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          style="width: 160px"
          format="yyyy"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.total }}
              <div class="desc">录取总数</div>
            </div>

            <div class="col">
              <span class="red">{{ row.evaluateStatus1 }}</span>
              <div class="desc">待评价</div>
            </div>
            <div class="col">
              {{ row.evaluateStatus2 }}
              <div class="desc">已评价</div>
            </div>
          </div>
          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <!-- <el-table
        v-if="showType == 1"
        v-loading="loading"
        :data="dataList"
        key="table1"
      >
        <el-table-column
          label="进修科目"
          align="center"
          prop="registerDeptName"
        />
        <el-table-column label="录取总数" align="center" prop="total" />
        <el-table-column label="待评价" align="center" prop="evaluateStatus1" />
        <el-table-column label="已评价" align="center" prop="evaluateStatus2" />
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="viewOpen(scope.row)"
              >查看名单
            </el-button>
          </template>
</el-table-column>
</el-table> -->
      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="col border" style="display: flex; flex: 8">
            <div>
              <div class="user-name">
                <div style="margin-right: 10px">
                  <el-checkbox
                    v-model="row.check"
                    style="transform: scale(1.2)"
                    @change="handleSelectionChange($event, index)"
                  />
                </div>
                <span
                  style="
                    font-size: 18px;
                    font-weight: bolder;
                    color: #a52529;
                    cursor: pointer;
                  "
                  @click="detailOpenInfo(row)"
                  >{{ row.userName }}</span
                >
                <div style="margin-left: auto; font-size: 12px; color: #999">
                  工号：{{ row.jobNumber }}
                </div>
              </div>
              <div class="info">
                <div class="flexInfo">
                  <div>进修科目：{{ row.registerDeptName }}</div>
                  <div style="display: flex">
                    进修期限：
                    <span v-if="row.registerNoticeVo"
                      >{{ row.registerNoticeVo.startDate }} -
                      {{ row.registerNoticeVo.endDate }}</span
                    >
                    <div v-if="row.durationName">
                      （{{ row.durationName }}）
                    </div>
                  </div>
                  <div>记录手册完成度：{{ row.manualTotal }}%</div>
                </div>
                <div class="flexInfo">
                  <div>
                    报到时间：{{
                      parseTime(
                        row.registerNoticeVo && row.registerNoticeVo.sureTime,
                        "{yyyy}/{mm}/{dd} {hh}:{ii}:{ss}"
                      )
                    }}
                  </div>
                  <div>考评分数：{{ row.scoreTotal }}</div>
                  <div>考评等级：{{ row.scoreLevel }}</div>
                </div>
              </div>
            </div>
          </div>

          <div class="col border">
            <div class="desc">评价状态</div>
            <div class="systemColor">
              {{ row.evaluateStatusName }}
            </div>
          </div>
          <div class="col border">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="sendOpen(row)"
              v-if="row.evaluateStatus == 1"
              >发送通知
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              @click="detailOpen(row)"
              v-if="row.evaluateStatus == 2"
              >评价详情
            </el-button>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="发送通知"
      :visible.sync="sendShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="sendForm"
        :model="sendForm"
        :rules="sendRules"
        label-width="80px"
      >
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            :rows="5"
            v-model="sendForm.content"
            placeholder="请输入通知内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendFormSubmit">确 定</el-button>
        <el-button @click="sendShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="查看评价表单"
      :visible.sync="lookShow"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <evaluatePreview />
      <div slot="footer" class="dialog-footer">
        <el-button @click="lookShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="设置评价时间"
      :visible.sync="settingShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="settingForm"
        :model="settingForm"
        :rules="settingRules"
        label-width="140px"
      >
        <el-form-item label="学员开始评价时间" prop="evaluateEndDay">
          带教结束前
          <el-input
            type="number"
            v-model="settingForm.evaluateEndDay"
            style="width: 100px; margin-left: 5px; margin-right: 5px"
          />
          天内
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="settingFormSubmit">确 定</el-button>
        <el-button @click="settingShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="查看评价详情"
      :visible.sync="detailShow"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <evaluatePreview v-if="detailShow" :register-id="registerId" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="报名详情"
      :visible.sync="detailShowInfo"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShowInfo"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShowInfo = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveEvaluateNoticeRegisterBase,
} from "@/api/business/registerBase";
import { listAllRegisterDept } from "@/api/business/registerDept";
import { listRegisterInfo } from "@/api/business/registerInfo";
import { setupBatchData } from "@/utils/batchUtils";

import { listAllRegisterType } from "@/api/business/registerType";
import { getSureInfo, updateSureInfo } from "@/api/business/sureInfo";
import evaluatePreview from "@/views/business/components/evaluatePreview.vue";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";

export default {
  name: "evaluate",
  components: { evaluatePreview, registerInfoDetailInfo },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      //全选
      AllCheck: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        // 仅查询未结业学员
        noEndStudy: 1,
        evaluateStatus: null,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: consts.registerBatchList,
      registerBaseVo: {},
      // 页面显示
      showType: 1,
      // 批量通知
      sendShow: false,
      sendForm: {},
      sendRules: {
        content: [
          { required: true, message: "通知内容不能为空", trigger: "blur" },
        ],
      },
      // 设置评价时间
      settingShow: false,
      settingForm: {},
      settingRules: {
        evaluateEndDay: [
          { required: true, message: "请输入天数", trigger: "blur" },
        ],
      },
      // 查看评价表单
      lookShow: false,
      // 评价详情
      registerId: null,
      detailShow: false,
      tagIndex: 0,
      detailShowInfo: false, // 报到详情
      registerInfo: {
        id: null,
      },
    };
  },
  async created() {
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    // 获取批次数据
    async getbatch() {
      await setupBatchData(this);
    },
    initData() {
      this.getCount();
      this.getList();
    },
    clickAll(index, value) {
      this.canselAllcheck();

      this.tagIndex = index;
      this.queryParams.evaluateStatus = value;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    getCount() {
      queryByCountRegisterBase(this.queryParams).then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total =
            this.registerBaseVo.evaluateStatus1 +
            this.registerBaseVo.evaluateStatus2;
        }
      });
    },
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].total =
              this.dataList[i].evaluateStatus1 +
              this.dataList[i].evaluateStatus2;
          }
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        listRegisterInfo(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.dataList.forEach((item) => {
            let manualTotal = 0;
            // 1、进修计划：完成进修计划，获得20%进度
            let progress = this.getTimeProgress(
              item.registerNoticeVo.startDate,
              item.registerNoticeVo.endDate
            );
            if (progress === 100) {
              manualTotal += 20;
              console.log(1);
            }
            // 2、进修考评：完成带教出科考评与考评结论，获得20%进度
            let registerAllocationVoList = item.registerAllocationVoList;
            if (
              registerAllocationVoList.length > 0 &&
              registerAllocationVoList.filter((e) => {
                return e.scoreStatus === 2;
              }).length === registerAllocationVoList.length
            ) {
              manualTotal += 20;
            }
            let registerManualVo = item.registerManualVo;
            if (registerManualVo) {
              // 3、个人小结：完成个人小结填写，获得20%进度
              if (registerManualVo.personalSummary) {
                manualTotal += 20;
              }
              // 4、临床工作：完成个人小结填写，获得20%进度
              if (
                registerManualVo.clinicNumber ||
                registerManualVo.emergencyNumber ||
                registerManualVo.averageNumber ||
                registerManualVo.clinicEmergencyContent ||
                registerManualVo.manageBeds ||
                registerManualVo.caseNumber ||
                registerManualVo.wardContent ||
                registerManualVo.businessContent ||
                registerManualVo.otherContent
              ) {
                manualTotal += 20;
              }
              // 5、进修评价：完成进修评价填写，获得20%进度
              if (
                registerManualVo.introduceFlag &&
                registerManualVo.planFlag &&
                registerManualVo.environmentFlag &&
                registerManualVo.teacherFlag &&
                registerManualVo.businessFlag &&
                registerManualVo.timecardFlag &&
                registerManualVo.examineFlag &&
                registerManualVo.strengthContent &&
                registerManualVo.improveContent
              ) {
                manualTotal += 20;
              }
            }
            item.manualTotal = manualTotal;
          });
          this.loading = false;
        });
      }
    },
    // 批量通知
    sendBatchOpen() {
      let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);
      for (let i = 0; i < list.length; i++) {
        if (list[i].evaluateStatus != 1) {
          this.$modal.msgError("请选择评价状态为待评价的数据");
          return;
        }
      }
      this.sendForm = {
        registerIdList: this.ids,
        content:
          "【华山医院】学员您好，请您登录系统在【记录手册-进修评价】模块填写本次学科培训工作评价！",
      };
      this.sendShow = true;
    },
    sendOpen(row) {
      this.sendForm = {
        registerIdList: [row.id],
        content:
          "【华山医院】学员您好，请您登录系统在【记录手册-进修评价】模块填写本次学科培训工作评价！",
      };
      this.sendShow = true;
    },
    sendFormSubmit() {
      this.$refs["sendForm"].validate((valid) => {
        if (valid) {
          saveEvaluateNoticeRegisterBase(this.sendForm).then((response) => {
            this.$modal.msgSuccess("通知成功");
            this.initData();
            this.sendShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 查看评价表单
    evaluateOpen() {
      this.lookShow = true;
    },
    // 设置评价时间
    settingOpen() {
      getSureInfo(1).then((response) => {
        this.settingForm = response.data;
        this.settingShow = true;
      });
    },
    settingFormSubmit() {
      this.$refs["settingForm"].validate((valid) => {
        if (valid) {
          updateSureInfo(this.settingForm).then((response) => {
            this.$modal.msgSuccess("设置成功");
            this.settingShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 查看评价内容
    detailOpen(row) {
      this.registerId = row.id;
      this.detailShow = true;
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    // 切换视图
    showTypeChange() {
      this.canselAllcheck();

      // 重置必要的状态
      this.ids = [];
      this.single = true;
      this.multiple = true;

      // 重置标签索引
      this.tagIndex = 0;

      // 只重置必要的查询参数
      this.queryParams = {
        ...this.queryParams, // 保留现有参数
        pageNum: 1,
        registerDeptId: null,
        userName: null,
        evaluateStatus: null,
      };

      // 触发查询
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();
      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.canselAllcheck();

      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
      console.log(this.multiple);
      console.log(this.single);
    },
    detailOpenInfo(row) {
      this.registerInfo.id = row.id;
      this.detailShowInfo = true;
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      console.log(checked, index);
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    getTimeProgress(startDateStr, endDateStr) {
      const startDate = new Date(startDateStr.replace(/-/g, "/"));
      const endDate = new Date(endDateStr.replace(/-/g, "/"));
      const now = new Date();
      if (now < startDate) {
        return 0;
      }
      if (now.getTime() >= endDate.getTime() - 12096e5) {
        return 100;
      }
      const totalDuration = endDate.getTime() - startDate.getTime();
      const elapsedDuration = now.getTime() - startDate.getTime();
      const progressPercentage = (elapsedDuration / totalDuration) * 100;
      return progressPercentage.toFixed(2);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

.user-name {
  display: flex;
  align-items: center;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  /* 控制列之间的间距 */
  background: #eeeff4;
  padding: 20px 0;
}

.box-container {
  padding: 0;
  padding-left: 20px;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 3);
      // font-weight: bolder;

      .desc {
        font-size: 12px;
        color: #888;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    // .title {
    //   font-size: 18px;
    //   text-align: left;
    //   margin-right: 180px;
    //   color: #000;
    // }

    // .func {
    //   font-size: 18px;
    //   color: #a52529;
    //   cursor: pointer;
    //   margin-left: 180px;
    // }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid rgb(232, 232, 232);
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;

      font-size: 14px;
      margin-top: 10px;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;
        width: 350px;

        line-height: 20px;
        flex: 1;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 600px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 150px;
    }

    .col:nth-child(3) {
      width: 150px;
    }

    .col:nth-child(4) {
      width: 150px;
    }

    .col:nth-child(5) {
      width: 150px;
    }
  }
}
</style>
